package studio.beamy.db.h2;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.tools.Server;
import studio.beamy.db.profile.DBConnectionSetup;

public class H2DbServer
{
	private DBConnectionSetup h2db;
	private Server server;

	public H2DbServer(DBConnectionSetup ds)
	{
		super();
		h2db = ds;
		this.server = initServer();
	}

	private Server initServer()
	{
		Server server = null;
		// -webAllowOthers, -tcpAllowOthers, -pgAllowOthers
		String[] args = null;
		try
		{
			if (new File(h2db.getBaseDir() + "/" + h2db.getDbName() + ".h2.db").exists())
			{
				args = new String[] { "-baseDir", h2db.getBaseDir(), "-tcpPort", h2db.getPort(), "-ifExists" };
				server = Server.createTcpServer(args);
				return server;
			}
			else
			{
				args = new String[] { "-baseDir", h2db.getBaseDir(), "-tcpPort", h2db.getPort() };
				server = Server.createTcpServer(args);
				server.start();
				Class.forName(h2db.getDbDriver());
				Connection conn = DriverManager.getConnection(h2db.getDbUrl(), h2db.getDbUser(), "");
				Statement stat = conn.createStatement();
				stat.execute("set password '" + h2db.getDbPwd() + "'");
				conn.close();
			}
			return server;
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		catch (ClassNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			server.stop();
		}
		return null;
	}

	public void startServer() throws SQLException
	{
		server.start();
	}

	public void stopServer()
	{
		if (server != null) server.stop();
	}
}